import { insertIntoTextarea } from '@gnlab/utils/env-browser/dom'
import { message, Button, Form, Checkbox, Input, InputNumber } from 'antd'
import type { TextAreaRef } from 'antd/lib/input/TextArea'
import services from '@/services'
import type { BaseMonitorConfig } from '@/services/features/group-monitor-apply'
import { MonitorGroupType, ApplyMessageVar } from '@/services/features/group-monitor-apply'
import type { EditingConfig } from '.'
import './EditConfig.module.less'

export default function EditConfig(props: {
  config: EditingConfig
  goPrev: (editedConfig: EditingConfig) => void
  onFinish: () => void
}) {
  const { config: initialConfig, goPrev, onFinish } = props
  const [form] = Form.useForm<EditingConfig>()

  const onGoPrev = useCallback(() => {
    const values = form.getFieldsValue()
    goPrev(values)
  }, [form, goPrev])

  const [submitting, setSubmitting] = useState(false)
  const onSubmit = useCallback(
    async (
      values: Omit<BaseMonitorConfig, 'ignoreApplyedDays'> & { ignoreApplyedDays: number | null },
    ) => {
      setSubmitting(true)
      const res = await services.features.groupMonitorApply.addOrUpdateConfig({
        id: initialConfig.id,
        ...values,
        ignoreApplyedDays: values.ignoreApplyedDays ?? 0,
      })
      setSubmitting(false)

      if (res.success) {
        void message.success('保存成功！')
        onFinish()
      } else {
        void message.warning(`保存失败：${res.error}`)
      }
    },
    [initialConfig, onFinish],
  )

  const applyMessageRef = useRef<TextAreaRef>(null)
  const insertVariable = useCallback(
    (variable: string) => {
      const textarea = applyMessageRef.current?.resizableTextArea?.textArea
      if (!textarea) return
      const result = insertIntoTextarea(textarea, `{${variable}}`)
      form.setFieldsValue({ applyMessage: result })
    },
    [applyMessageRef, form],
  )

  return <Form
    styleName="form"
    form={form}
    initialValues={initialConfig}
    labelCol={{ span: 5 }}
    onFinish={onSubmit}
  >
    <Form.Item name="wxids" hidden>
      <Input />
    </Form.Item>
    <Form.Item name="enable" hidden>
      <Input />
    </Form.Item>

    <Form.Item name="name" label="任务名称" rules={[{ required: true }]}>
      <Input maxLength={30} />
    </Form.Item>

    <Form.Item name="types" label="监控群类型">
      <Checkbox.Group
        options={[
          { label: '本企业外部群', value: MonitorGroupType.CorpExternal },
          { label: '非本企业外部群', value: MonitorGroupType.External },
        ]}
      />
    </Form.Item>

    <Form.Item label="不添加" styleName="ignore-items">
      <Form.Item name="ignoreApplyedByOther" valuePropName="checked">
        <Checkbox>已被其他企微添加为好友的联系人</Checkbox>
      </Form.Item>

      <Form.Item name="ignoreApplyed" valuePropName="checked">
        <Checkbox>
          <Form.Item name="ignoreApplyedDays">
            <ApplyedDaysInput />
          </Form.Item>
        </Checkbox>
      </Form.Item>
    </Form.Item>

    <Form.Item
      label="每日发送申请上限"
      name="dailyLimit"
      rules={[{ required: true }]}
      extra={
        <div styleName="daily-limit-tips">
          经测试，一个完成企业认证和实名，并且权重较好的企微号，每日群内加人发送申请上限在 800~1000
          次左右。
        </div>
      }
    >
      <InputNumber />
    </Form.Item>

    <Form.Item
      styleName="apply-message"
      label="加好友验证消息"
      name="applyMessage"
      rules={[{ required: true }]}
      extra={
        <div styleName="apply-message-variables">
          <span>插入变量：</span>
          <a onClick={() => insertVariable(ApplyMessageVar.QywxName)}>企微账号昵称</a>
          <a onClick={() => insertVariable(ApplyMessageVar.MemberName)}>对方微信昵称</a>
          <a onClick={() => insertVariable(ApplyMessageVar.GroupName)}>群名称</a>
        </div>
      }
    >
      <Input.TextArea
        ref={applyMessageRef}
        rows={5}
        placeholder="少于48个汉字"
        maxLength={48}
        showCount
      />
    </Form.Item>

    <Form.Item styleName="actions">
      <Button disabled={submitting} onClick={onGoPrev}>
        上一步
      </Button>
      <Button loading={submitting} type="primary" htmlType="submit">
        完成
      </Button>
    </Form.Item>
  </Form>
}

function ApplyedDaysInput(props: { value?: number; onChange?: (value: number) => void }) {
  const { value, onChange } = props
  return <div styleName="applyed-days">
    过去 <InputNumber min={0} value={value} onChange={value => onChange?.(value ?? 0)} />{' '}
    天内发送过好友申请的人
  </div>
}
